package com.feihua.starter.web.modules.hdb.mvc;

import com.feihua.framework.rest.ResponseJsonRender;
import com.feihua.framework.rest.interceptor.RepeatFormValidator;
import com.feihua.framework.rest.modules.common.mvc.BaseController;
import com.feihua.starter.comm.Constants;
import com.feihua.starter.comm.component.MsgTemplate;
import com.feihua.starter.service.api.ApiHdbActivityPoService;
import com.feihua.starter.service.api.ApiHdbAttendPoService;
import com.feihua.starter.service.api.ApiHdbMsgPoService;
import com.feihua.starter.service.api.ApiHdbUserExtendPoService;
import com.feihua.starter.service.modules.hdb.dto.HdbActivityDto;
import com.feihua.starter.service.modules.hdb.dto.HdbAttendDto;
import com.feihua.starter.service.modules.hdb.dto.HdbUserExtendDto;
import com.feihua.starter.service.modules.hdb.dto.SearchHdbAttendsConditionDto;
import com.feihua.starter.service.modules.hdb.po.HdbActivityPo;
import com.feihua.starter.service.modules.hdb.po.HdbAttendPo;
import com.feihua.starter.service.modules.hdb.po.HdbMsgPo;
import com.feihua.utils.http.httpServletResponse.ResponseCode;
import feihua.jdbc.api.pojo.BasePo;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.utils.OrderbyUtils;
import feihua.jdbc.api.utils.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 活动吧参与用户管理
 * Created by revolver
 */
@RestController
@RequestMapping("/hdb")
public class HdbAttendController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(HdbAttendController.class);

    @Autowired
    private ApiHdbAttendPoService apiHdbAttendPoService;
    @Autowired
    private ApiHdbMsgPoService apiHdbMsgPoService;
    @Autowired
    private ApiHdbActivityPoService apiHdbActivityPoService;
    @Autowired
    private ApiHdbUserExtendPoService apiHdbUserExtendPoService;

    /**
     * 单资源，添加
     *
     * @param hdbAttendDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:add")
    @RequestMapping(value = "/attend", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody HdbAttendDto hdbAttendDto) {
        logger.info("添加活动吧参与用户开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        HdbAttendPo basePo = new HdbAttendPo();
        BeanUtils.copyProperties(hdbAttendDto, basePo);
        basePo.setUserId(getLoginUserId());

        apiHdbAttendPoService.preInsert(basePo, getLoginUser().getId());
        HdbAttendDto r = apiHdbAttendPoService.insert(basePo);
        if (r == null) {
            // 添加失败
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("添加活动吧参与用户结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 添加成功，返回添加的数据
            //发消息
            final HdbActivityDto hdbActivityDto = apiHdbActivityPoService.selectByPrimaryKey(basePo.getActivityId());
            HdbMsgPo msgPo = new HdbMsgPo();
            msgPo.setReadFlag(BasePo.YesNo.N.name());
            msgPo.setUserId(basePo.getUserId());
            msgPo.setActivityId(basePo.getActivityId());
            msgPo.setSources(Constants.MsgSource.MSG_SYSTEM.getCode());
            msgPo.setTitle(Constants.MsgSource.MSG_SYSTEM.getName());
            msgPo.setContent(String.format(MsgTemplate.attend_activity_msg, hdbActivityDto.getTitle()));
            apiHdbMsgPoService.preInsert(msgPo, getLoginUserId());
            apiHdbMsgPoService.insert(msgPo);

            //检查名额是事满了，更新状态
            HdbAttendPo countQuery = new HdbAttendPo();
            countQuery.setStatus(BasePo.YesNo.Y.name());
            countQuery.setActivityId(hdbActivityDto.getId());
            countQuery.setDelFlag(BasePo.YesNo.N.name());
            Integer count = apiHdbAttendPoService.count(countQuery);
            if (hdbActivityDto.getHeadcount() != null && hdbActivityDto.getHeadcount().equals(count)) {
                HdbActivityPo po = new HdbActivityPo();
                po.setId(hdbActivityDto.getId());
                po.setStatus(Constants.ActivityStatus.QUOTA_FULL.getCode());
                po.setUpdateAt(new Date());
                apiHdbActivityPoService.updateByPrimaryKeySelective(po);

                //给领队发条消息
                msgPo = new HdbMsgPo();
                msgPo.setReadFlag(BasePo.YesNo.N.name());
                msgPo.setUserId(hdbActivityDto.getLedUserId());
                msgPo.setActivityId(basePo.getActivityId());
                msgPo.setSources(Constants.MsgSource.MSG_ACTIVITY.getCode());
                msgPo.setTitle(Constants.MsgSource.MSG_ACTIVITY.getName());
                msgPo.setContent(String.format(MsgTemplate.quota_full_activity_msg, hdbActivityDto.getTitle()));
                apiHdbMsgPoService.preInsert(msgPo, getLoginUserId());
                apiHdbMsgPoService.insert(msgPo);
            }

            resultData.setData(r);
            logger.info("添加活动吧参与用户id:{}", r.getId());
            logger.info("添加活动吧参与用户结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:delete")
    @RequestMapping(value = "/attend/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable String id) {
        logger.info("删除活动吧参与用户开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动吧参与用户id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbAttendPoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动吧参与用户结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动吧参与用户id:{}", id);
            logger.info("删除活动吧参与用户结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源，更新
     *
     * @param hdbAttendDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:update")
    @RequestMapping(value = "/attend", method = RequestMethod.PUT)
    public ResponseEntity update(@RequestBody HdbAttendDto hdbAttendDto) {
        logger.info("更新活动吧参与用户开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        logger.info("活动吧参与id:{}", hdbAttendDto.getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        HdbAttendPo basePo = new HdbAttendPo();
        // id
        BeanUtils.copyProperties(hdbAttendDto, basePo);

        apiHdbAttendPoService.preUpdate(basePo, getLoginUser().getId());
        int r = apiHdbAttendPoService.updateByPrimaryKeySelective(basePo);
        if (r <= 0) {
            // 更新失败，资源不存在
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("更新活动吧参与用户结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新成功，已被成功创建
            logger.info("更新的活动吧参与id:{}", basePo.getId());
            logger.info("更新活动吧参与用户结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，退出活动更新
     *
     * @param hdbAttendDto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:quit")
    @RequestMapping(value = "/attend/quit", method = RequestMethod.PUT)
    public ResponseEntity quit(@RequestBody HdbAttendDto hdbAttendDto) {
        logger.info("更新活动吧参与用户退出开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        logger.info("活动吧参与id:{}", hdbAttendDto.getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbAttendPo hdbAttendPo = apiHdbAttendPoService.selectByPrimaryKeySimple(hdbAttendDto.getId());
        hdbAttendPo.setStatus(BasePo.YesNo.N.name());
        apiHdbAttendPoService.preUpdate(hdbAttendPo, getLoginUser().getId());
        int r = apiHdbAttendPoService.updateByPrimaryKeySelective(hdbAttendPo);
        if (r <= 0) {
            // 更新失败，资源不存在
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("更新活动吧参与用户退出结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新成功，已被成功创建
            final HdbActivityDto hdbActivityDto = apiHdbActivityPoService.selectByPrimaryKey(hdbAttendPo.getActivityId());
            //发消息
            HdbMsgPo msgPo = new HdbMsgPo();
            msgPo.setReadFlag(BasePo.YesNo.N.name());
            msgPo.setUserId(hdbAttendPo.getUserId());
            msgPo.setActivityId(hdbAttendPo.getActivityId());
            msgPo.setSources(Constants.MsgSource.MSG_SYSTEM.getCode());
            msgPo.setTitle(Constants.MsgSource.MSG_SYSTEM.getName());
            String selfContent = "";
            HdbUserExtendDto hdbUserExtendDto = apiHdbUserExtendPoService.selectByPrimaryKey(hdbAttendPo.getUserId());
            if (getLoginUserId().equals(hdbAttendPo.getUserId())) {
                //自己操作退出
                selfContent = String.format(MsgTemplate.quit_activity_msg_self, hdbActivityDto.getTitle());
            } else {
                //领队操作退出
                selfContent = String.format(MsgTemplate.quit_activity_msg_manager, hdbActivityDto.getTitle());

            }
            msgPo.setContent(selfContent);
            apiHdbMsgPoService.preInsert(msgPo, getLoginUserId());
            apiHdbMsgPoService.insert(msgPo);
            if (Constants.ActivityStatus.QUOTA_FULL.getCode().equals(hdbActivityDto.getStatus())) {
                HdbActivityPo po = new HdbActivityPo();
                po.setId(hdbActivityDto.getId());
                po.setStatus(Constants.ActivityStatus.APPLYING.getCode());
                po.setUpdateAt(new Date());
                apiHdbActivityPoService.updateByPrimaryKeySelective(po);

            }
            //给领队发条消息
            msgPo = new HdbMsgPo();
            msgPo.setReadFlag(BasePo.YesNo.N.name());
            msgPo.setUserId(hdbActivityDto.getLedUserId());
            msgPo.setActivityId(hdbActivityDto.getId());
            msgPo.setSources(Constants.MsgSource.MSG_SYSTEM.getCode());
            msgPo.setTitle(Constants.MsgSource.MSG_SYSTEM.getName());
            msgPo.setContent(String.format(MsgTemplate.quit_activity_msg, hdbUserExtendDto.getNickname(), hdbActivityDto.getTitle(), getLoginUser().getNickname()));
            apiHdbMsgPoService.preInsert(msgPo, getLoginUserId());
            apiHdbMsgPoService.insert(msgPo);

            logger.info("更新的活动吧参与id:{}", hdbAttendPo.getId());
            logger.info("更新活动吧参与用户退出结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，获取id活动吧参与用户
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:getById")
    @RequestMapping(value = "/attend/{id}", method = RequestMethod.GET)
    public ResponseEntity getById(@PathVariable String id) {

        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbAttendDto baseDataScopeDto = apiHdbAttendPoService.selectByPrimaryKey(id, false);
        if (baseDataScopeDto != null) {
            resultData.setData(baseDataScopeDto);
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 复数资源，搜索活动吧参与用户
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:attend:search")
    @RequestMapping(value = "/attends", method = RequestMethod.GET)
    public ResponseEntity search(SearchHdbAttendsConditionDto dto) {

        ResponseJsonRender resultData = new ResponseJsonRender();
        PageAndOrderbyParamDto pageAndOrderbyParamDto = new PageAndOrderbyParamDto(PageUtils.getPageFromThreadLocal(), OrderbyUtils.getOrderbyFromThreadLocal());
        // 设置当前登录用户id
        PageResultDto<HdbAttendDto> list = apiHdbAttendPoService.searchByMultiTable(dto, pageAndOrderbyParamDto);

        if (CollectionUtils.isNotEmpty(list.getData())) {
            resultData.setData(list.getData());
            resultData.setPage(list.getPage());
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }
}
